<template>
	<el-select ref='select' v-model="val" :filterable="filterable" :clearable="showClose" v-bind="$attrs"
		@hook:mounted="visileChange" @visible-change="visileChange" @blur="onblur" v-on="$listeners">
		<slot></slot>
	</el-select>
</template>
<script>
	import common from "/src/common/common.js";

	export default {
		name: "elSelect2",
		props: {
			clearable: { //是否显示清空按钮
				type: Boolean,
				default: true
			},
			filterable: { //是否可以搜索
				type: Boolean,
				default: true
			},
			//搜索附带数据
			value: {
				type: Number | String | Object,
				default: null
			}, //当前值
		},
		watch: {
			value: function(n, old) {}
		},

		computed: {
			val: {
				get: function() {
					return this.value;
				},
				set: function(n, old) {
					this.selectChange(n);
				}
			}
		},

		data: function() {
			return {
				showClose: false
			};
		},

		created: function() {
			this.init();
		},

		methods: {
			eventListener(e) {
				this.$refs.select.filterMethod(e.target.value);
			},
			bindRemote() { //必须this.$nextTick 解决IOS下remote-method输入第一个字没反应的BUG
				const innerElInput = this.$refs.select.$refs.reference;
				innerElInput.$el.getElementsByTagName('input');
				// 获取input元素
				const inputEle = innerElInput.$el.getElementsByTagName('input')[0];
				// 主动触发远程搜索方法
				inputEle.removeEventListener('input', this.eventListener);
				inputEle.addEventListener('input', this.eventListener);
			},
			init() {
				//解决IOS输入了不去请求的情况
				this.$nextTick(() => {
					this.bindRemote();
				});
			},
			visileChange(e) { //hook:mounted visible-change调用
				if (e && this.clearable) { // 打开下拉框 显示可清空按钮,解决要点击两次的BUG
					this.showClose = true;
				}
				//解决不弹出输入框的BUG
				this.$nextTick(() => {
					if (!e) {
						const {
							select
						} = this.$refs;
						const input = select.$el.querySelector('.el-input__inner');
						input.removeAttribute('readonly');
					}
				});
			},
			onblur() { //失去焦点 不会自动隐藏输入框的BUG
				setTimeout(() => {
					if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { //判断iPhone|iPad|iPod|iOS
						this.$refs.select.blur();
					}
					this.showClose = false
					var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
					window.scrollTo(0, Math.max(scrollHeight - 1, 0));
				}, 100);
			},
			selectChange: function(n) {
				this.$emit("input", n);
			}
		}
	}
</script>
